package lixp.shiro.config;

import lixp.pojo.UpmsPermission;
import lixp.pojo.UpmsRole;
import lixp.pojo.UpmsUser;
import lixp.shiro.service.ShiroService;
import lixp.utils.Md5util;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class MyRealm extends AuthorizingRealm {

    Logger logger = LoggerFactory.getLogger("MyRealm.class");

    @Autowired
    ShiroService shiroService;



    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("------授权操作--------");
//        String username = (String) principalCollection.getPrimaryPrincipal();
//        UpmsUser upmsUser = shiroService.getUpmUserByUserName(username);

        UpmsUser upmsUser = (UpmsUser) principalCollection.getPrimaryPrincipal();

        // 当前用户所有角色
        List<UpmsRole> upmsRoles = shiroService.selectUpmsRoleByUpmsUserId(upmsUser.getUserId());
        Set<String> roles = new HashSet<>();
        for (UpmsRole upmsRole : upmsRoles) {
            if (StringUtils.isNotBlank(upmsRole.getName())) {
                roles.add(upmsRole.getName());
            }
        }

        // 当前用户所有权限
        List<UpmsPermission> upmsPermissions = shiroService.selectUpmsPermissionByUpmsUserId(upmsUser.getUserId());
        Set<String> permissions = new HashSet<>();
        for (UpmsPermission upmsPermission : upmsPermissions) {
            if (StringUtils.isNotBlank(upmsPermission.getPermissionValue())) {
                permissions.add(upmsPermission.getPermissionValue());
            }
        }
        logger.info("----"+roles.toString());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;

    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("------认证操作--------");

        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        logger.info("----"+username+"----"+password);

        UpmsUser upmsUser = shiroService.getUpmUserByUserName(username);
        //判断用户是否存在
        if (null == upmsUser) {
            throw new UnknownAccountException();
        }
        //判断密码是否正确，这里用了md5+盐的方式
        if (!upmsUser.getPassword().equals(Md5util.md5String(password + upmsUser.getSalt()).toUpperCase())) {
            logger.error("------------------");
            throw new IncorrectCredentialsException();
        }
        //判断用户是否锁定
        if (upmsUser.getLocked() == 1) {
            throw new LockedAccountException();
        }

        //本来真正的登录验证是在这里进行，但是由于进行了MD5加密，用起来比较麻烦，所以验证就在上面进行，因此这里要的密码应该和传入进来的一样
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(upmsUser,password,upmsUser.getUsername());

        return info;
    }
}
